package com.wit.witmg.exception;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.wit.witmg.util.ErrorCode;
import com.wit.witmg.util.JsonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;


/**
 * 
* @Title: GlobalExceptionHandler
* @Description: 全局异常处理
如果使用@RestControllerAdvice 注解
则会将返回的数据类型转换成JSON格式
* @Version:1.0.0  
* @author pancm
* @date 2018年10月24日
 */
@ControllerAdvice
public class GlobalExceptionHandler {

	private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
	/**
	 * 处理自定义的业务异常
	 * @param req
	 * @param e
	 * @return
	 */
    @ExceptionHandler(value = BizException.class)  
    @ResponseBody  
	public  Object bizExceptionHandler(HttpServletRequest req, BizException e){
    	logger.error("发生业务异常！原因是：{}",e.getErrorMsg());
//		logService.exceptLog(req,501,"发生业务异常！原因是："+e.getMessage());
    	return JsonResult.error(ErrorCode.ERR_502);
    }

	/**
	 * 处理空指针的异常
	 * @param e
	 * @return
	 */
	@ExceptionHandler(value =NullPointerException.class)
	@ResponseBody
	public Object exceptionHandler(HttpServletRequest req,NullPointerException e){
		logger.error("发生空指针异常！原因是:",e);
//		logService.exceptLog(req,500,"发生空指针异常！原因是:"+e.toString());
		return JsonResult.error(ErrorCode.ERR_501);
	}


    /**
        * 处理其他异常
     * @param e
     * @return
     */

	@ResponseBody
	@ExceptionHandler(Exception.class)
	public Object handleException(HttpServletRequest req,Exception e) {
		String msg = e.getMessage();
		ErrorCode errorCode;
		if (msg == null || msg.equals("")) {
			errorCode=ErrorCode.ERR_500;
		}else if(msg.contains("token")){
			errorCode=ErrorCode.ERR_400;
		}else if(msg.equals("非法请求")){
			errorCode=ErrorCode.ERR_101;
		}else if(msg.equals("请求超时")){
			errorCode=ErrorCode.ERR_102;
		}else if(msg.equals("不能重复请求")){
			errorCode=ErrorCode.ERR_100;
		}else if(msg.equals("签名校验错误")){
			errorCode=ErrorCode.ERR_103;
		}else if(msg.equals(ErrorCode.ERR_302.getMsg())){
			errorCode=ErrorCode.ERR_302;
		}else if(msg.equals("店铺已到期")){
			errorCode=ErrorCode.ERR_301;
		}else if(msg.equals("黑名单")){
			errorCode=ErrorCode.ERR_305;
		}else if(msg.equals("抱歉!手机号不能为空,请重新登录")){
			errorCode=ErrorCode.ERR_400;
		}else{
			errorCode=ErrorCode.ERR_0;
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("code",errorCode.getCode());
		jsonObject.put("result",-1);
		jsonObject.put("message", errorCode.getCode()==0?e.getMessage(): errorCode.getMsg());
		StringBuilder sb = new StringBuilder();
		Enumeration<String> handNames=req.getHeaderNames();
		while (handNames.hasMoreElements()) {
			String paraName = handNames.nextElement();
			String paraVal = req.getHeader(paraName);
			if (!Strings.isNullOrEmpty(paraName)) {
				sb.append(paraName).append("=").append(paraVal).append("&");
			}
		}
		Enumeration<String> parameterNames = req.getParameterNames();
		while (parameterNames.hasMoreElements()) {
			String paraName = parameterNames.nextElement();
			String paraVal = req.getParameter(paraName);
			if (!Strings.isNullOrEmpty(paraName)) {
				sb.append(paraName).append("=").append(paraVal).append("&");
			}
		}
		String s = sb.toString();
//		logService.exceptLog(req,errorCode.getCode(),msg+"->"+req.getRequestURI()+"->"+s+"<<<<"+jsonObject.toString());
		return jsonObject;
	}

}
